package com.app.micaihu.manager;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.android.volley.VolleyError;
import com.app.micaihu.R;
import com.app.micaihu.adapter.MainFragmentTabAdapter;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.config.ServiceDeliveryData;
import com.app.micaihu.bean.news.NewsEntity;
import com.app.micaihu.configure.ConfigKeyConstant;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.custom.view.CustomImageView;
import com.app.micaihu.custom.view.dialog.DismisiDialog;
import com.app.micaihu.listener.AutoHeightControllerListener;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.utils.DialogUtils;
import com.app.micaihu.utils.HttpUtils;
import com.app.micaihu.view.user.usertask.UserTaskActivity;
import com.app.utils.util.DateUtils;
import com.app.utils.util.ViewSizeUtils;
import com.app.utils.util.image.LoadImageUtils;
import com.facebook.imagepipeline.image.ImageInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * Created by Guo on 2017/7/4.
 * <p>
 * <p>
 * 服务器配置的活动的管理类
 */

public class ServiceDeliveryManager {


    public static final String DELIVERY_POSITION_MAIN = "0";//首页位置
//    public static final String DELIVERY_POSITION_USER = "1";//我的位置

    public static final String DELIVERY_METHOD_DIALOG = "0";//弹窗
//    public static final String DELIVERY_METHOD_BANNER = "1";//banner轮播


    public static final String DELIVERY_SHOW_TYPE_ONCE = "0";//只展示一次
    public static final String DELIVERY_SHOW_TYPE_ONCE_A_DAY = "1";//每天展示一次
    public static final String DELIVERY_SHOW_TYPE_EVERY = "2";//永久展示_banner_____ios的说法是每次启动都弹


    private static ServiceDeliveryManager serviceDeliveryManager;


    private static ArrayList<ServiceDeliveryData> mMainQueue = new ArrayList<ServiceDeliveryData>(); //创建一个列表来存放dialog模型
    //    private static ArrayList<ServiceDeliveryData> mUserQueue = new ArrayList<ServiceDeliveryData>(); //创建一个列表来存放dialog模型
    private static ArrayList<ServiceDeliveryData> localDataList;
    private static MainFragmentTabAdapter mainFragmentTabAdapter;
    private Activity currentActivity;
    private String currentLocation;
    private Dialog dialog;


    private ServiceDeliveryManager() {

    }


    public static ServiceDeliveryManager getSingleton() {
        if (serviceDeliveryManager == null) {
            synchronized (ServiceDeliveryManager.class) {
                if (serviceDeliveryManager == null) {
                    serviceDeliveryManager = new ServiceDeliveryManager();
                }
            }
        }

        return serviceDeliveryManager;
    }


    /**
     * 处理服务器的数据
     *
     * @param activityList
     */
    public void dealServiceDiliveryData(List<ServiceDeliveryData> activityList) {
        if (activityList != null && activityList.size() > 0) {
            //创建gson.来本地化
            Gson gson = new Gson();
            //创建个list 保存我的banner
            ArrayList<ServiceDeliveryData> userBannerList = null;

            //创建活动的list,保存活动
            ArrayList<ServiceDeliveryData> mainList = null;

            for (ServiceDeliveryData serviceDeliveryData :
                    activityList) {
                //先区位置
                if (serviceDeliveryData != null) {
                    String positionType = serviceDeliveryData.getPositionType();
                    String displayType = serviceDeliveryData.getDisplayType();
                    if (DELIVERY_POSITION_MAIN.equals(positionType)) {//首页只有一个.所以直接用覆盖的写法来写
                        if (DELIVERY_METHOD_DIALOG.equals(displayType)) {
                            if (mainList == null) {
                                mainList = new ArrayList<>();
                            }
                            mainList.add(serviceDeliveryData);
                        }

                    }

//                    else if (DELIVERY_POSITION_USER.equals(positionType)) {
//                        if (DELIVERY_METHOD_DIALOG.equals(displayType)) {
//                            if (mainList == null) {
//                                mainList = new ArrayList<>();
//                            }
//                            mainList.add(serviceDeliveryData);
//                        }
//
//                        if (DELIVERY_METHOD_BANNER.equals(displayType)) {
//                            if (userBannerList == null) {
//                                userBannerList = new ArrayList<>();
//                            }
//                            userBannerList.add(serviceDeliveryData);
//                        }
//
//                    }
                }
            }

            if (mainList == null) {
                mainList = new ArrayList<>();
            }

            //模拟一个登陆红包的数据
//            ServiceDeliveryData dataLogin = new ServiceDeliveryData();
//            dataLogin.setShowFrequency(DELIVERY_SHOW_TYPE_EVERY);
//            dataLogin.setPositionType(DELIVERY_POSITION_MAIN);
//            dataLogin.setExtraData(1);
//            dataLogin.setActivityId("-1");
//
////
//
//            mainList.add(0, dataLogin);


            //先判断这次  有没有首页活动
            if (mainList == null || mainList.size() < 1) {
                //将其至为"";
                AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.main_activity, "");

            } else {//这次 有首页活动
                //将本地数据拿出来
                String s = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.main_activity, "");

                ArrayList<ServiceDeliveryData> localData = gson.fromJson(s, new TypeToken<ArrayList<ServiceDeliveryData>>() {
                }.getType());


                //将本地的 上次显示的时间更新给新的数据
                if (localData != null && localData.size() > 0) {
                    for (int i = 0; i < mainList.size(); i++) {
                        for (int j = 0; j < localData.size(); j++) {
                            if (TextUtils.equals(mainList.get(i).getActivityId(), localData.get(j).getActivityId())) {
                                mainList.get(i).setDate(localData.get(j).getDate());
                            }
                        }
                    }
                }
                //存入本地
                String mainStr = gson.toJson(mainList);
                if (!TextUtils.isEmpty(mainStr)) {
                    AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.main_activity, mainStr);
                }
            }

            //我的 的banner
//            if (userBannerList != null && userBannerList.size() > 0) {
//                String userBannerListStr = gson.toJson(userBannerList);
//                AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.user_banner, userBannerListStr);
//            } else {
//                AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.user_banner, "");
//            }

        } else {
//            AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.user_banner, "");
            AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.main_activity, "");
        }


    }


    public int getCurrentFragment() {
        if (mainFragmentTabAdapter != null) {
            return mainFragmentTabAdapter.getCurrentTab();
        }
        return -1;
    }


    /**
     * 将本地数据处理成队列
     * <p>
     * 在Main 初始化的时候调用.Main初始化意味着重新开启的当前的App,所以重新初始化队列
     */
    public void dealActivityQueue(MainFragmentTabAdapter mainFragmentTabAdapter) {
        if (mainFragmentTabAdapter == null) return;

        if (this.mainFragmentTabAdapter == null || this.mainFragmentTabAdapter != mainFragmentTabAdapter) {
            this.mainFragmentTabAdapter = mainFragmentTabAdapter;
            mMainQueue.clear();
//            mUserQueue.clear();
        }

        //拿到本地中,关于弹窗的 所有数据
        String s = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.main_activity, "");
        if (TextUtils.isEmpty(s)) return;//如果本地没有数据,那么证明没有活动
        //讲本地的数据 解析成object
        Gson gson = new Gson();
        localDataList = gson.fromJson(s, new TypeToken<ArrayList<ServiceDeliveryData>>() {
        }.getType());

        if (localDataList != null && localDataList.size() > 0) {
            for (ServiceDeliveryData serviceDeliveryData : localDataList) {
                //拿到的数据 是已经带日期的了,带日期表示今日已经显示过了


                //判断,如果有活动id一样的.就不再进行判断了,直接不加入
                for (ServiceDeliveryData ser : mMainQueue) {
                    if (ser.getActivityId().equals(serviceDeliveryData.getActivityId())) {
                        serviceDeliveryData.setShowFrequency("-1");
                    }
                }
//
//                for (ServiceDeliveryData ser :mUserQueue){
//                    if(ser.getActivityId().equals(serviceDeliveryData.getActivityId())){
//                        serviceDeliveryData.setShowFrequency("-1");
//                    }
//                }


                //显示频率
                String showFrequency = serviceDeliveryData.getShowFrequency();

                //根据频率_比对是否展示过了
                if (DELIVERY_SHOW_TYPE_ONCE.equals(showFrequency)) {//只显示一次的
                    boolean flag = AppConfigManager.getInstance().readConfig(serviceDeliveryData.getActivityId(), false);
                    //默认是没显示过
                    if (!flag) {
                        if (DELIVERY_POSITION_MAIN.equals(serviceDeliveryData.getPositionType())) {
                            mMainQueue.add(serviceDeliveryData);
                        }
//                        else if (DELIVERY_POSITION_USER.equals(serviceDeliveryData.getPositionType())) {
//                            mUserQueue.add(serviceDeliveryData);
//                        }
                    }
                } else if (DELIVERY_SHOW_TYPE_ONCE_A_DAY.equals(showFrequency)) {//每天显示一次的
                    String date = serviceDeliveryData.getDate();
                    if (TextUtils.isEmpty(date)) { //表示今日没显示过
                        if (DELIVERY_POSITION_MAIN.equals(serviceDeliveryData.getPositionType())) {
                            mMainQueue.add(serviceDeliveryData);
                        }
//                        else if (DELIVERY_POSITION_USER.equals(serviceDeliveryData.getPositionType())) {
//                            mUserQueue.add(serviceDeliveryData);
//                        }

                    } else {//如果对比时间,上一次日期比今日日期要小,.也加入队列

                        String currentDate = DateUtils.getCurrentTime("yyyy-MM-dd");
                        String lastDate = serviceDeliveryData.getDate();

                        if (lastDate.compareTo(currentDate) < 0) {
                            if (DELIVERY_POSITION_MAIN.equals(serviceDeliveryData.getPositionType())) {
                                mMainQueue.add(serviceDeliveryData);
                            }
//                            else if (DELIVERY_POSITION_USER.equals(serviceDeliveryData.getPositionType())) {
//                                mUserQueue.add(serviceDeliveryData);
//                            }
                        }
                    }
                } else if (DELIVERY_SHOW_TYPE_EVERY.equals(showFrequency)) {//永久显示的(每次启动都显示)
//                    if (!serviceDeliveryData.isShowInThisLaunch()) {//没展示过,则加入队列
                    if (DELIVERY_POSITION_MAIN.equals(serviceDeliveryData.getPositionType())) {
                        mMainQueue.add(serviceDeliveryData);
                    }
//                    else if (DELIVERY_POSITION_USER.equals(serviceDeliveryData.getPositionType())) {
//                        mUserQueue.add(serviceDeliveryData);
//                    }
//                    }
                }
            }
        }
    }

    private ServiceDeliveryData currentData = null;//当次 取出来的 活动moudle
    private ArrayList<ServiceDeliveryData> mQueue = null;//当前的活动 的列表


    /**
     * 展示活动的dialog
     *
     * @param activity
     * @param location
     */
    public synchronized void showActivityDialog(Activity activity, String location) {
        this.currentActivity = activity;
        this.currentLocation = location;

        if (currentActivity == null || currentActivity.isFinishing()) return;

//        if (DELIVERY_POSITION_USER.equals(currentLocation)) {
//            mQueue = mUserQueue;
//        } else
//
        if (DELIVERY_POSITION_MAIN.equals(currentLocation)) {
            mQueue = mMainQueue;
        }
        if (mQueue == null || mQueue.size() <= 0) return;
        boolean login = UserInforManager.getInstance().isLogin();
        for (ServiceDeliveryData ser : mQueue) {
            //先判断,用户登录没登录
//            if(currentData != null && currentData.getActivityId().equals(ser.getActivityId())){
//                currentData = null;
//                continue;
//            }
            currentData = null;
            //如果已经显示过了.就不显示了
            if (ser.isShowInThisLaunch()) {
                currentData = null;
                continue;
            }
            if (ser.getExtraData() == 1) {
                if (!login) {
                    currentData = ser;
                    break;
                } else {
                    continue;
                }
            }
            //如果登录了
            if (login) {
                currentData = ser;
                break;
            } else {
                //如果没登录
                if (!ser.getIsLogin()) {
                    currentData = ser;
                    break;
                }
            }
        }
        if (currentData == null) return;

//        if (currentData.getExtraData() == 1) {//如果view 不为null,那么就用自定义的,是红包
//            hongbao(null, dialogListener);
//        } else {
            normalActivity();
//        }


    }


    private void showDialog(View activityDialog) {
        dialog = new DismisiDialog(this.currentActivity, R.style.CustomDialogStyle);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnKeyListener(dialogListener);
        dialog.requestWindowFeature(Window.FEATURE_ACTION_MODE_OVERLAY);
        dialog.show();
        if (dialog.getWindow() != null) {
            dialog.getWindow().getAttributes().gravity = Gravity.CENTER;
//            dialog.getWindow().setWindowAnimations(R.style.dialogWindowAnim2);
            WindowManager.LayoutParams attributes = dialog.getWindow().getAttributes();
            attributes.width = ViewSizeUtils.dp2px(this.currentActivity, 310);
            dialog.getWindow().setAttributes(attributes);
            dialog.setCancelable(true);
        }
        dialog.setContentView(activityDialog);
    }


    /**
     * 普通的活动
     */

    private void normalActivity() {
        final View activityDialog = LayoutInflater.from(this.currentActivity).inflate(R.layout.dialog_activity, null);
        View cancle = activityDialog.findViewById(R.id.iv_cancle);
        final CustomImageView thumb = (CustomImageView) activityDialog.findViewById(R.id.thumb);

        final String thumbUrl = currentData.getThumb();
        LoadImageUtils.getInstance().downloadImage(thumbUrl, new LoadImageUtils.OnImageDownloadedListener() {
            @Override
            public void loadImage() {
                currentActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        LoadImageUtils.getInstance().loadImage(thumb, thumbUrl);
                        LoadImageUtils.getInstance().loadImage(thumb, thumbUrl, new AutoHeightControllerListener<ImageInfo>(thumb, 560));
                        showDialog(activityDialog);
                        if (currentData != null) {
                            if (DELIVERY_SHOW_TYPE_ONCE.equals(currentData.getShowFrequency())) {
                                AppConfigManager.getInstance().writeConfig(currentData.getActivityId(), true);
                            } else if (DELIVERY_SHOW_TYPE_ONCE_A_DAY.equals(currentData.getShowFrequency())) {
                                String currentDate = DateUtils.getCurrentTime("yyyy-MM-dd");
                                currentData.setDate(currentDate);
                            }
                            currentData.setShowInThisLaunch(true);
                            try {
                                for (ServiceDeliveryData ser : localDataList) {
                                    if (TextUtils.equals(ser.getActivityId(), currentData.getActivityId())) {
                                        ser.setDate(currentData.getDate());
                                        ser.setShowInThisLaunch(currentData.isShowInThisLaunch());
                                    }
                                }
                                Gson gson = new Gson();
                                String changedData = gson.toJson(localDataList);

                                AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.main_activity, changedData);

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
            }

            @Override
            public void fail(String error) {

            }
        });


        final NewsEntity newsEntity = new NewsEntity();
        newsEntity.setArticleId(currentData.getArticleId());
        newsEntity.setArticleType(currentData.getArticleType());
        newsEntity.setJumpUrl(currentData.getJumpUrl());
        thumb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null) {
                    dialog.dismiss();
                }
                //得根据jumpUrl 来确定跳转到哪里
                if (newsEntity != null) {

                    String jumpUrl = newsEntity.getJumpUrl();
                    if (!TextUtils.isEmpty(jumpUrl)) {
                        if (jumpUrl.startsWith("activity://openSign")) {
                            currentActivity.startActivity(new Intent(currentActivity, UserTaskActivity.class));
                        } else {
                            TypeConstant.openTypeDetail(newsEntity, currentActivity, null);

                        }
                    } else {
//                        ShareUtils.getInstance().setSharePageSource(ShareUtils.HuoDongPage);
                        TypeConstant.openTypeDetail(newsEntity, currentActivity, null);

                    }
                }


            }
        });


        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null) {
                    dialog.dismiss();
                }
                showActivityDialog(currentActivity, currentLocation);
            }
        });
    }


    /**
     *登陆注册的红包,伪造数据
     * @param dialogListener
     */
//    public void hongbao(Activity activity,DialogInterface.OnKeyListener dialogListener) {
//        final Activity hbActivity;
//        if(activity == null) {
//            hbActivity = currentActivity;
//        }else{
//            hbActivity = activity;
//        }
//
//        if(hbActivity == null || hbActivity.isFinishing()) return;
//
//
//
//        View hongbaoDialog = LayoutInflater.from(hbActivity).inflate(R.layout.dialog_newhongbao, null);
//        View cancle = hongbaoDialog.findViewById(R.id.iv_cancel);
//
//        TextView bounds = (TextView) hongbaoDialog.findViewById(R.id.tv_bounds);
//        String boundText = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.register_money, "1.0");
//        if (!TextUtils.isEmpty(boundText)) {
//            bounds.setText("¥" + StringUtils.toFloat(boundText, 1.0f));
//        } else {
//            bounds.setVisibility(View.GONE);
//        }
//        TextView register = (TextView) hongbaoDialog.findViewById(R.id.tv_register);
//        register.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                DialogUtils.getInstance().dismissCDialog();
//                UserInforManager.getInstance().toLoginPage(hbActivity);
//            }
//        });
//        cancle.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                DialogUtils.getInstance().dismissCDialog();
//                showActivityDialog(currentActivity,currentLocation);
//            }
//        });
//        HashMap<String, Object> dialogParams = new HashMap<>();
//        dialogParams.put("width", 280);
//        dialogParams.put("touchOutside", false);
//        dialogParams.put("anim", R.style.dialogWindowAnim2);
//        DialogUtils.getInstance().showCDialog(hongbaoDialog,hbActivity,dialogParams, dialogListener);
//        if(currentData != null){
//            currentData.setShowInThisLaunch(true);
//
//        }
//    }


    /**
     * 请求 活动接口
     * <p>
     * (用于刷新)
     */
    public void requestActivity() {
        HashMap<String, String> param = new HashMap<>();
        if (UserInforManager.getInstance().getUserInfor() != null) {
            param.put("uid", UserInforManager.getInstance().getUserInfor().getUid());
        } else {
            param.put("uid", "");
        }
        HttpListener<DataBean<List<ServiceDeliveryData>>> activityListener = new HttpListener<DataBean<List<ServiceDeliveryData>>>() {
            @Override
            public void onError(VolleyError error) {
            }

            @Override
            public void onSuccess(DataBean<List<ServiceDeliveryData>> response) {
                if (response.noErrorData()) {
                    dealServiceDiliveryData(response.getData());
                    dealActivityQueue(mainFragmentTabAdapter);
                }
            }
        };
        HttpUtils.addPostRequest(URIContant.ACTIVITY_HUODONG, new TypeToken<DataBean<List<ServiceDeliveryData>>>() {
        }.getType(), "", param, activityListener);
    }


//    DismisiDialog.OnDismissListener mOnDismissListener = new DismisiDialog.OnDismissListener() {
//        @Override
//        public void onDismiss() {
////            if(currentActivity == AppManager.getAppManager().getLastActivity()){
//                showActivityDialog(currentActivity,currentLocation);
////            }
//        }
//    };


    DialogInterface.OnKeyListener dialogListener = new DialogInterface.OnKeyListener() {

        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {

            if (dialog == dialog) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
                    DialogUtils.getInstance().dismissCDialog();
                    showActivityDialog(currentActivity, currentLocation);
                }

                return true;
            }

            return false;


        }


    };


}
